package com.gomoku.controller;

import example.*;
import javafx.fxml.FXML;
import javafx.scene.layout.Pane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.util.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundSize;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;

public class GameController {
    private static final int BOARD_SIZE = 15;
    private static final int TILE_SIZE = 40;
    private int currentPlayer = 1;
    private Border board;
    private Stack<Move> undoStack = new Stack<>();
    private Timeline gameTimer;
    private int secondsElapsed = 0;
    private List<String> backgroundImages = new ArrayList<>();
    private int currentBackgroundIndex = 0;

    // 新增：计时器暂停状态
    private boolean isTimerPaused = false;
    // 新增：计时器暂停时累计的时间
    private int pausedSeconds = 0;

    private static class Move {
        int x, y, player;
        Move(int x, int y, int player) {
            this.x = x;
            this.y = y;
            this.player = player;
        }
    }

    @FXML private Pane gameBoard;
    @FXML private Label player1Label;
    @FXML private Label player2Label;
    @FXML private Label currentTurnLabel;
    @FXML private Label timerLabel;
    @FXML private Button restartButton;
    @FXML private Button undoButton;
    @FXML private Button resignButton;
    @FXML private Button changeBackgroundButton;

    @FXML
    private void initialize() {
        board = new Border();

        // 初始化背景图片列表
        backgroundImages.add(getClass().getResource("/com/gomoku/images/board1.png").toExternalForm());
        backgroundImages.add(getClass().getResource("/com/gomoku/images/board2.png").toExternalForm());
        backgroundImages.add(getClass().getResource("/com/gomoku/images/board3.png").toExternalForm());
        backgroundImages.add(getClass().getResource("/com/gomoku/images/board4.png").toExternalForm());
        backgroundImages.add(getClass().getResource("/com/gomoku/images/board5.png").toExternalForm());
        backgroundImages.add(getClass().getResource("/com/gomoku/images/board6.png").toExternalForm());

        drawBoard();
        updatePlayerInfo();
        startGameTimer();  // 修改：使用新的计时器启动方法
    }

    // 新增：改进的计时器启动方法
    private void startGameTimer() {
        gameTimer = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
            if (!isTimerPaused) {
                secondsElapsed++;
                updateTimerDisplay();
            }
        }));
        gameTimer.setCycleCount(Timeline.INDEFINITE);
        gameTimer.play();
    }

    // 新增：暂停计时器
    private void pauseTimer() {
        isTimerPaused = true;
        pausedSeconds = secondsElapsed;
    }

    // 新增：恢复计时器
    private void resumeTimer() {
        isTimerPaused = false;
        secondsElapsed = pausedSeconds;
    }

    // 新增：重置计时器
    private void resetTimer() {
        secondsElapsed = 0;
        isTimerPaused = false;
        pausedSeconds = 0;
        updateTimerDisplay();
    }

    private void updateTimerDisplay() {
        Platform.runLater(() -> {
            int minutes = secondsElapsed / 60;
            int seconds = secondsElapsed % 60;
            timerLabel.setText(String.format("%02d:%02d", minutes, seconds));
        });
    }

    private void updatePlayerInfo() {
        player1Label.setText("玩家1 (黑棋)");
        player2Label.setText("玩家2 (白棋)");
        currentTurnLabel.setText("当前回合: " + (currentPlayer == 1 ? "玩家1 (黑棋)" : "玩家2 (白棋)"));
    }

    private void drawBoard() {
        gameBoard.getChildren().clear();
        changeBoardBackground();

        for (int i = 0; i < BOARD_SIZE; i++) {
            Line hLine = new Line(0, i * TILE_SIZE, (BOARD_SIZE - 1) * TILE_SIZE, i * TILE_SIZE);
            hLine.setStroke(Color.BLACK);

            Line vLine = new Line(i * TILE_SIZE, 0, i * TILE_SIZE, (BOARD_SIZE - 1) * TILE_SIZE);
            vLine.setStroke(Color.BLACK);

            gameBoard.getChildren().addAll(hLine, vLine);
        }

        gameBoard.setOnMouseClicked(this::handleMove);
    }

    @FXML
    private void handleMove(MouseEvent event) {
        double clickX = event.getX();
        double clickY = event.getY();
        int x = (int) Math.round(clickX / TILE_SIZE);
        int y = (int) Math.round(clickY / TILE_SIZE);

        if (x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE) {
            if (board.checkMove(x, y)) {
                undoStack.push(new Move(x, y, currentPlayer));
                board.move(x, y, new Player(currentPlayer));
                placeStone(x, y, currentPlayer == 1);

                if (board.isWin(x, y, new Player(currentPlayer))) {
                    showWinner(currentPlayer);
                    gameBoard.setOnMouseClicked(null);
                    // 新增：游戏结束时停止计时器
                    gameTimer.stop();
                } else {
                    currentPlayer = 3 - currentPlayer;
                    updatePlayerInfo();
                }
            }
        }
    }

    private void placeStone(int x, int y, boolean isBlack) {
        ImageView stone = new ImageView();
        try {
            stone.setImage(new Image(isBlack ?
                    "/com/gomoku/images/black_stone.png" :
                    "/com/gomoku/images/white_stone.png"));
        } catch (Exception e) {
            javafx.scene.shape.Circle circle = new javafx.scene.shape.Circle(
                    x * TILE_SIZE, y * TILE_SIZE, 15,
                    isBlack ? Color.BLACK : Color.WHITE
            );
            circle.setStroke(Color.BLACK);
            gameBoard.getChildren().add(circle);
            return;
        }

        stone.setFitWidth(32);
        stone.setFitHeight(32);
        stone.setLayoutX(x * TILE_SIZE - 16);
        stone.setLayoutY(y * TILE_SIZE - 16);
        gameBoard.getChildren().add(stone);
    }

    @FXML
    private void handleChangeBackground() {
        currentBackgroundIndex = (currentBackgroundIndex + 1) % backgroundImages.size();
        changeBoardBackground();
    }

    private void changeBoardBackground() {
        try {
            String imageUrl = backgroundImages.get(currentBackgroundIndex);
            BackgroundImage backgroundImage = new BackgroundImage(
                    new Image(imageUrl),
                    BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT,
                    BackgroundPosition.CENTER,
                    new BackgroundSize(100, 100, true, true, true, true)
            );
            gameBoard.setBackground(new Background(backgroundImage));
        } catch (Exception e) {
            System.err.println("背景图片加载失败: " + e.getMessage());
        }
    }

    @FXML
    private void handleRestart() {
        board = new Border();
        undoStack.clear();
        currentPlayer = 1;

        // 修改：使用新的计时器重置方法
        resetTimer();
        if (gameTimer != null) {
            gameTimer.stop();
        }
        startGameTimer();

        updatePlayerInfo();
        drawBoard();
    }

    @FXML
    private void handleUndo() {
        if (!undoStack.isEmpty()) {
            // 新增：暂停计时器
            pauseTimer();

            Move lastMove = undoStack.pop();
            board.undoMove(lastMove.x, lastMove.y);
            currentPlayer = lastMove.player;
            updatePlayerInfo();
            redrawBoard();

            // 新增：恢复计时器
            resumeTimer();
        }
    }

    private void redrawBoard() {
        gameBoard.getChildren().clear();
        changeBoardBackground();

        for (int i = 0; i < BOARD_SIZE; i++) {
            Line hLine = new Line(0, i * TILE_SIZE, (BOARD_SIZE - 1) * TILE_SIZE, i * TILE_SIZE);
            hLine.setStroke(Color.BLACK);

            Line vLine = new Line(i * TILE_SIZE, 0, i * TILE_SIZE, (BOARD_SIZE - 1) * TILE_SIZE);
            vLine.setStroke(Color.BLACK);

            gameBoard.getChildren().addAll(hLine, vLine);
        }

        for (int x = 0; x < BOARD_SIZE; x++) {
            for (int y = 0; y < BOARD_SIZE; y++) {
                if (board.getChessboard()[x][y] == 1) {
                    placeStone(x, y, true);
                } else if (board.getChessboard()[x][y] == 2) {
                    placeStone(x, y, false);
                }
            }
        }

        gameBoard.setOnMouseClicked(this::handleMove);
    }

    @FXML
    private void handleResign() {
        int winner = 3 - currentPlayer;
        showWinner(winner);
        gameBoard.setOnMouseClicked(null);
        // 新增：认输时停止计时器
        gameTimer.stop();
    }

    private void showWinner(int winner) {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("游戏结束");
        alert.setHeaderText(null);
        alert.setContentText("玩家" + winner + "获胜!\n游戏时长: " + timerLabel.getText());
        alert.showAndWait();
    }

    @FXML
    private void handleMainMenu() {
        if (gameTimer != null) {
            gameTimer.stop();
        }
        SceneManager.loadScene("StartView");
    }
}